/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Ref, SetupContext, ShallowRef, nextTick, ref } from 'vue';
import { TabsProps } from '../tabs.props';
import { TabPageContext, UseTabs } from './types';

export function useTabs(
    props: TabsProps,
    context: SetupContext,
    tabNavigationElementRef: ShallowRef<any>
): UseTabs {
    // 存储tab的props数组
    const tabPages = ref<TabPageContext[]>([]);
    // 激活状态的tabId
    const activeId = ref(props.activeId || '');
    // 显示下拉面板
    const hideDropDown = ref(true);

    const toolbarItems = ref<any>([]);

    function setActiveId(tabPages: Ref<TabPageContext[]>) {
        const index = tabPages.value.findIndex((tabPage: TabPageContext) =>
            tabPage.props.show !== false && !activeId.value && !tabPage.props.disabled);
        if (!activeId.value && index !== -1) {
            activeId.value = tabPages.value[index].props.id;
        }
    }

    function changeTitleStyle(tabNavigationElementRef: ShallowRef<any>) {
        if (props.autoTitleWidth) {
            return;
        }
        const $textEls = tabNavigationElementRef.value?.querySelectorAll('.st-tab-text');
        if (!$textEls) {
            return;
        }
        for (let k = 0; k < $textEls.length; k++) {
            const parentEl = $textEls[k].parentNode as any;
            if ($textEls[k].scrollWidth > parentEl.offsetWidth) {
                if (!$textEls[k].classList.contains('farris-title-text-custom')) {
                    $textEls[k].classList.add('farris-title-text-custom');
                }
            } else {
                $textEls[k].classList.remove('farris-title-text-custom');
            }
        }
    }

    const stopBubble = ($event: MouseEvent) => {
        $event.preventDefault();
        $event.stopPropagation();
    };

    function removeTab($event: MouseEvent, targetTabId: string, closeDropdown = false) {
        const index = tabPages.value.findIndex((tabPage: TabPageContext) => tabPage.props.id === targetTabId);
        tabPages.value = tabPages.value.filter((tabPage: TabPageContext) => tabPage.props.id !== targetTabId);
        if (activeId.value === targetTabId) {
            activeId.value = '';
            setActiveId(tabPages);
        }
        stopBubble($event);
        nextTick(() => {
            changeTitleStyle(tabNavigationElementRef);
            if (closeDropdown) {
                hideDropDown.value = true;
            }
            const index = tabPages.value.findIndex((tabPage: TabPageContext) => tabPage.props.id === activeId.value);
            context.emit('tabRemove', {
                removeIndex: index,
                removeId: targetTabId,
                activeId: activeId.value
            });
        });
    }

    function selectTabByTabId(targetTabId: string) {
        const prevId = activeId.value;
        activeId.value = targetTabId;
        const activePage = tabPages.value.find((tabPageContext: TabPageContext) => tabPageContext.props.id === targetTabId);
        if (activePage && activePage.props.toolbar && activePage.props.toolbar.contents && activePage.props.toolbar.contents.length) {
            toolbarItems.value = [...activePage.props.toolbar.contents];
        }
        context.emit('tabChange', {
            prevId,
            nextId: activeId.value
        });
    }

    function selectTab(targetTabId: string) {
        selectTabByTabId(targetTabId);
    };

    /**
     * 增加新页签
     * @param target 标签页上下文对象
     */
    function addTab(target: TabPageContext) {
        const index = tabPages.value.findIndex((tabPage: TabPageContext) => tabPage.props.id === target.props.id);
        if (index === -1) {
            tabPages.value.push(target);
        }
    };

    /**
     * 更新页签标题
     * @param target 标签页上下文对象
     */
    function updateTab(target: TabPageContext) {
        const index = tabPages.value.findIndex((tabPage: TabPageContext) => tabPage.props.id === target.props.id);
        if (index === -1) {
            return;
        }
        tabPages.value.forEach((tabPage: TabPageContext) => {
            if (tabPage.props.id === target.props.id) {
                tabPage = target;
            }
        });
        nextTick(() => {
            changeTitleStyle(tabNavigationElementRef);
        });
    };

    return {
        activeId,
        addTab,
        changeTitleStyle,
        removeTab,
        selectTab,
        selectTabByTabId,
        tabPages,
        updateTab,
        toolbarItems
    };
}
